<?php

namespace addons\kzvote\controller\store;

use app\common\model\kzvote\music\Music;
use app\common\model\kzvote\Log as LogModel;
use app\common\model\kzvote\Vote as VoteModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Exception;
use think\exception\DbException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Log extends BaseController
{

    /**
     * 查看
     * @throws DbException
     * @throws Exception
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $votes = VoteModel::where('user_id', $user['id'])
            ->where('status','<',30)->field('id,name')->select();

        if ($this->request->isAjax()) {
            $params = $this->request->param();
            $vote_ids = array_column((array)$votes,'id');
            $where['log.vote_id'] = ['in', $vote_ids];

            if ($params['vote_id']){
                if (!in_array($params['vote_id'], $vote_ids)){
                    $this->error('请筛选自己的活动');
                }
                $where['log.vote_id'] = $params['vote_id'];
            }
            if ($params['person_id']){
                $where['person_id'] = $params['person_id'];
            }
            if ($params['type']){
                $where['log.type'] = $params['type'];
            }
            if ($params['name']){
                $where['person.name'] = ['like',"%{$params['name']}%"];
            }
            if ($params['createtime']){
                $where['log.createtime'][] = ['>=',strtotime($params['createtime'][0])];
                $where['log.createtime'][] = ['<=',strtotime($params['createtime'][1])];
            }
            $log = new LogModel;
            $list = $log->alias('log')
                ->with(['vote','person'])
                ->where($where)
                ->order('id desc')
                ->paginate(10);

            $result = array("total" => $list->total(), "rows" => $list->items());
            $this->success('','',$result);
        }
        return $this->view->fetch();
    }

    public function export(){
        set_time_limit(0);
        $user = $this->auth->getUser();
        $votes = VoteModel::where('user_id', $user['id'])
            ->where('status','<',30)->field('id,name')->select();

        $params = $this->request->param();
        $vote_ids = array_column((array)$votes,'id');
        $where['log.vote_id'] = ['in', $vote_ids];

        if ($params['vote_id']){
            if (!in_array($params['vote_id'], $vote_ids)){
                $this->error('请筛选自己的活动');
            }
            $where['log.vote_id'] = $params['vote_id'];
        }
        if ($params['person_id']){
            $where['person_id'] = $params['person_id'];
        }
        if ($params['type']){
            $where['log.type'] = $params['type'];
        }
        if ($params['name']){
            $where['person.name'] = ['like',"%{$params['name']}%"];
        }
        if ($params['createtime']){
            $params['createtime'] = explode(',',$params['createtime']);
            $where['log.createtime'][] = ['>=',strtotime($params['createtime'][0])];
            $where['log.createtime'][] = ['<=',strtotime($params['createtime'][1])];
        }
        $log = new LogModel;
        $list = $log->alias('log')
            ->with(['vote','person','user'])
            ->where($where)
            ->order('id desc')
            ->paginate($params['limit']);

        //开始制作表格
        $spreadsheet = new Spreadsheet();
        $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);

        $worksheet = $spreadsheet->setActiveSheetIndex(0);

        $file_name = '投票记录导出'.date('Y-m-d');

        $worksheet->getCell('A1')->setValue('投票活动');
        $worksheet->getCell('B1')->setValue('作品名称');
        $worksheet->getCell('C1')->setValue('投票用户');
        $worksheet->getCell('D1')->setValue('投票ip');
        $worksheet->getCell('E1')->setValue('投票方式');
        $worksheet->getCell('F1')->setValue('票数');
        $worksheet->getCell('G1')->setValue('投票时间');
        $worksheet->getCell('H1')->setValue('表单内容');

        $ABC = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];

        $arr = [];
        foreach ($list as $key => $val) {
            $form = '';
            if ($val['join_form']){
                foreach ($val['join_form'] as $k=>$row){
                    $form .= $k.":".$row."​\n​";
                }
            }
            $type = ['常规投票','看视频投票','礼物投票'];

            $data = array($val['vote']['name'], $val['person']['name'], $val['user']['nickname'],$val['ip'],$type[$val['type']-1]
            ,$val['num'], $val['createtime_text'], $form);

            array_push($arr, $data);
        }

        foreach ($arr as $key => $row) {
            foreach ($ABC as $k => $r) {
                $worksheet->getCell($ABC[$k] . ($key + 2))->setValue($row[$k]);
            }
        }
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        //下载文档
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
    }


}
